//
//  KLMLoginController.swift
//  KLM_GN
//
//  Created by Nic on 2025/2/20.
//

import UIKit

class KLMLoginController: KLMBaseController {

    @IBOutlet weak var mailTextField: UITextField!
    @IBOutlet weak var passTextField: UITextField!
    @IBOutlet weak var logBtn: UIButton!
    @IBOutlet weak var eyeBtn: UIButton!
    
//    @IBOutlet weak var signUpBtn: UIButton!
    @IBOutlet weak var forgotPasswordBtn: UIButton!
    
    ///隐私政策
    @IBOutlet weak var privacyView: UIView!
    @IBOutlet weak var agreeBtn: UIButton!
    @IBOutlet weak var agreeLabel: UILabel!
    
    @IBOutlet weak var userPrivacyBtn: UIButton!
    @IBOutlet weak var andLabel: UILabel!
    @IBOutlet weak var privacyPolicyBtn: UIButton!
    
    
    @IBOutlet weak var logoView: UIImageView!
    @IBOutlet weak var componyNameLabel: UILabel!
    
    
    private var popView: YBPopupMenu?
    private var popLists: [KLMUserCache]?
    
    ///是否是其他用户登录
    var isOtherLogin: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupData()
        events()
        
        let rightItem = KLMBaseButton()
        navigationItem.rightBarButtonItem = UIBarButtonItem.itemWithBaseButton(rightItem, target: self, action: #selector(register(_:)), configBlock: { baseItem in
            baseItem.configStyle(with: KLMLocalizable.LANGLOC("Sign Up"), font: UIFont(safeName: "PingFangSC-Medium", size: 16), titleColor: appMainThemeColor)
        })
    }
    
    override func viewDidLoadConfig() {
        super.viewDidLoadConfig()
        
        logoView.image = UIImage.image(withColor: appMainThemeColor, size: logoView.size, cornerRadius: 12)
        componyNameLabel.configStyle(with: "智谋纪", font: UIFont(safeName: "PingFangSC-Medium", size: 21), titleColor: rgba(38, 38, 38, 1))
        
        KLMLog("login")
        logBtn.isEnabled = false
        logBtn.configStyle(with: KLMLocalizable.LANGLOC("Log In"), font: UIFont(safeName: "PingFangSC-Regular", size: 18), titleColor: .white, bgImage: UIImage.init(color: appMainThemeColor))
        logBtn.configStyle(bgImage: UIImage.init(color: appMainThemeColor.withAlphaComponent(0.5)), state: .disabled)
        logBtn.layer.cornerRadius = logBtn.height / 2
        logBtn.clipsToBounds = true
        
        NotificationCenter.default.addObserver(self, selector: #selector(setupData), name: .loginPageRefresh, object: nil)
        mailTextField.font = UIFont(safeName: "PingFangSC-Medium", size: 16)
        passTextField.font = UIFont(safeName: "PingFangSC-Medium", size: 16)
        
        passTextField.addTarget(self, action: #selector(textChange(_:)), for: .editingChanged)
        mailTextField.placeholder =  KLMLocalizable.LANGLOC("Mobile number/Email")
        passTextField.placeholder = KLMLocalizable.LANGLOC("Password")
        agreeLabel.text = KLMLocalizable.LANGLOC("I agree to")
        andLabel.text = KLMLocalizable.LANGLOC("And")
//        已阅读并同意《用户协议》和《隐私政策》
        privacyPolicyBtn.configStyle(with: "《" + KLMLocalizable.LANGLOC("Privacy Policy") + "》", titleColor: rgba(28, 136, 229, 1))
        userPrivacyBtn.configStyle(with: "《" + KLMLocalizable.LANGLOC("User Protocol") + "》", titleColor: rgba(28, 136, 229, 1))
        agreeBtn.configStyle(image: "icon_no_select")
        agreeBtn.configStyle(image: "icon_select", state: .selected)
        
        eyeBtn.configStyle(image: "icon_invisible")
        eyeBtn.configStyle(image: "icon_visual", state: .selected)
        
        forgotPasswordBtn.configStyle(with: KLMLocalizable.LANGLOC("Forgot Password"), font: UIFont(safeName: "PingFangSC-Medium", size: 14), titleColor: rgba(38, 38, 38, 1))
    }
    @objc func textChange(_ textField: UITextField) {
        logBtn.isEnabled = false
        if let account = mailTextField.text, !account.isEmpty, let pwd = passTextField.text, !pwd.isEmpty {
            logBtn.isEnabled = true
        }
    }
    @IBAction func tapUserPrivacy(_ sender: UIButton) {
        let vc = WHWebViewController()
        vc.urlString = "https://www.kinglumi.com/about/privacy-policy"
        vc.loadingProgressColor = appMainThemeColor
        navigationController?.pushViewController(vc, animated: true)
    }
    @IBAction func tapPrivacyPolicy(_ sender: UIButton) {
        let vc = WHWebViewController()
        vc.urlString = "https://www.kinglumi.com/about/privacy-policy"
        vc.loadingProgressColor = appMainThemeColor
        navigationController?.pushViewController(vc, animated: true)
    }
    @objc func setupData() {
        if let username = KLMUserDefault.getValue(for: .username) {
            self.mailTextField.text = username as? String
        }
        if let password = KLMUserDefault.getValue(for: .password) {
            self.passTextField.text = password as? String
        }
    }
    private func events() {
        if isOtherLogin {
            isOtherLogin = false
            ///弹出提示框
            KLMAlertController.showAlertWithTitle(title: nil, message: KLMLocalizable.LANGLOC("Your account is logged in on other devices"))
        }
    }
    @IBAction func login(_ sender: Any) {
        if agreeBtn.isSelected == false {
            SVProgressHUD.showInfo(withStatus: KLMLocalizable.LANGLOC("Please agree to the Privacy Policy"))
            return
        }
        
        guard let mailText = KLMTool.isEmptyString(string: mailTextField.text) else {
            SVProgressHUD.showInfo(withStatus: mailTextField.placeholder)
            return
        }
        
        guard let passText = KLMTool.isEmptyString(string: passTextField.text) else {
            SVProgressHUD.showInfo(withStatus: passTextField.placeholder)
            return
        }
        SVProgressHUD.show()
        KLMRequest.login(username: mailText, password: passText) { response in
            SVProgressHUD.dismiss()
            ///进入主页面
            self.switchRootVc(vc: KLMTabBarController())
            
        } failure: { error in
            
            KLMHttpShowError(error)
        }
//        KLMService.login(username: mailText, password: passText) { _ in
//            SVProgressHUD.dismiss()
//            ///进入主页面
//            self.switchRootVc(vc: KLMTabBarController())
//            
//        } failure: { error in
//            
//            KLMHttpShowError(error)
//        }
    }
    
    @objc func register(_ sender: Any) {
        let register = KLMRegisterPhoneController()
        navigationController?.pushViewController(register, animated: true)
    }
    
    @IBAction func forgetPass(_ sender: Any) {
        ///账号是邮箱
        if let text = mailTextField.text, KLMVerifyManager.isEmail(email: text) {
            let vc = KLMForgotEmailPasswordController()
            navigationController?.pushViewController(vc, animated: true)
            return
        }
        let vc = KLMForgotPhonePasswordController()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func eyeBtn(_ sender: UIButton) {
        passTextField.isSecureTextEntry = !passTextField.isSecureTextEntry
        sender.isSelected = !sender.isSelected
    }
    
    @IBAction func didBegin(_ sender: Any) {
        
        showPopView()
    }
    
    @IBAction func editingChanged(_ textField: UITextField) {
        
        showPopView()
        
        textChange(textField)
    }
    
    @IBAction func agreementClick(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        
        if let account = mailTextField.text, !account.isEmpty, let pwd = passTextField.text, !pwd.isEmpty {
            logBtn.isEnabled = sender.isSelected
        }
    }
    
    private func showPopView() {
        
        let accountLists = KLMUser.getAccountLists()
        var titles = accountLists?.map({$0.account}) as? [String]
        if let account = mailTextField.text, !account.isEmpty {
            titles = titles?.filter({$0.hasPrefix(account)})
        }
        popLists = accountLists?.filter({ cache in
            guard let titles = titles else { return false }
            if let account = cache.account, titles.contains(account) {
                return true
            }
            return false
        })
        if let popView = popView { ///弹过弹框
            ///dismiss和dismissOnSelected = true delegate = nil,这里重新赋值一下
            popView.delegate = self
            if let titles: [String] = titles, titles.count > 0 {
//                popView.titles = titles
                popView.show()
            } else {
                popView.dismiss()
            }
        } else { ///没弹过
            let menuViewrect: CGRect = mailTextField.convert(mailTextField.bounds, to: KLMKeyWindow)
            let point: CGPoint = CGPoint.init(x: menuViewrect.origin.x, y: menuViewrect.origin.y + menuViewrect.size.height)
            if let titles: [String] = titles {
                YBPopupMenu.show(at: point, titles: titles, icons: nil, menuWidth: 200) { popupMenu in
                    popupMenu?.priorityDirection = .none
                    popupMenu?.arrowHeight = 0
                    popupMenu?.minSpace = menuViewrect.origin.x
                    popupMenu?.dismissOnSelected = false
                    popupMenu?.isShadowShowing = false
                    popupMenu?.delegate = self
                    popupMenu?.cornerRadius = 10
                    self.popView = popupMenu
                }
            }
        }
    }
}

extension KLMLoginController: YBPopupMenuDelegate {
    
    func ybPopupMenu(_ ybPopupMenu: YBPopupMenu!, didSelectedAt index: Int) {
        ybPopupMenu.dismiss()
        let account = popLists![index]
        mailTextField.text = account.account
        passTextField.text = account.password
    }
}
